<template>
	<view class="">
		<!--  -->
		<ben></ben>
		<!--  -->
		<!-- 顶部 -->
		<view class="head_back padbottom30">
			<view class="row posrel align_item_c" :style="{ paddingTop: topHight + 'px' }">
				<view class="head_right posabs" style="left: 30rpx;" @click="tab">
					<text class="size28 font500 colf" v-if="!isEdit">编辑</text>
					<text class="size28 font500 colf" v-else>编辑</text>
				</view>
				<view class="font600 colf font_italic disflex just_cont_c flex1" style="font-size: 25px;">
					购物车
				</view>
			</view>
		</view>
		<!-- 顶部 -->
		<view class="content">
			<!-- 商品商家列表是空的 -->
			<view class="empty" style="margin-top: 300rpx;" v-if="loadmore.length == 0">
				<u-empty mode="car" icon="https://cdn.uviewui.com/uview/empty/car.png">
				</u-empty>
			</view>
			<!-- 商品商家列表 -->
			<view class="" v-else>
				<view class="cartShop column" v-for="(items, index) in list" :key="index">
					<!-- 商家列表 -->
					<view class="cartName cartPad">
						<view class="cart-xxkbk">
							<radio :checked="items.shopSelected == 1" color="#FF3F00" style="transform:scale(0.8)"
								@click="shopselect(items)" />
						</view>
						<view class="cartName-box">
							<image :src="items.shop.stores_logo" class="cartName-img rad1"></image>
							<view class="omit1 size26 col3 font600" style="max-width:400rpx;">
								{{ items.shop.stores_name }}
							</view>
						</view>
					</view>
					<!-- 商品列表 -->
					<view class="min20_rl row" style="margin-bottom: 20rpx;" v-for="(item, k) in items.products"
						:key="k" @click="goodSelect(items, item)">
						<view class="minto">
							<radio :checked="item.goodsSelected == 1" color="#FF3F00" style="transform:scale(0.8)" />
						</view>
						<view class="rad1">
							<image :src="item.image" class="cartDetail-imgs rad1"></image>
						</view>
						<view class="column minleft10 flex1">
							<view class="size28 col3 font600 omit1">{{ item.title }}</view>
							<view class="size24 col9 font500 mintop10">
								规格：{{ item.specs.name }}
							</view>
							<view class="cartNum minto minbottom0">
								<view class="cartNum-txt size30 font500" style="color:#FE3C3C;">
									￥
									<text class="size36">{{ item.specs.selling_price }}</text>
								</view>
								<view class="add-sub-con">
									<u-number-box v-model="item.specs.specs_num" :disabledInput="true" buttonSize="22"
										@change="getCarnum($event,item.car_id)"></u-number-box>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view style="margin-top: 50rpx;"><u-loadmore :status="status" /></view>
			</view>
		</view>
		<!-- 底部选项卡 -->
		<view class="cartTotal" :style="{ bottom: safeBottom + 'px',width: screenWidth + 'px' }" v-if="!isEdit">
			<view class="row align_item_c">
				<radio :checked="allSelected" color="#FF3F00" style="transform:scale(0.8)" @click="selectAllAction" />
				<view class="size28" @click="selectAllAction">全选</view>
			</view>
			<view class="cart-num column minleft20">
				<view class="cart-numTxt row align_item_c">
					合计：
					<view class="size22 font500" style="color: #FE3C3C;">
						￥
						<text class="font600 size30">{{ total.totalPrice }}</text>
					</view>
				</view>
				<view class="size24 font500 mintop20" style="color: #4A4A4A;">
					消费可得{{ total.totalIntegral }}积分
				</view>
			</view>
			<view class="row minau minright0">
				<view class="column" style="width: 180rpx;">
					<view class="font500 size24 col6 minbottom10" style="text-align: end;">
						共{{ total.totalNum }}件商品
					</view>
					<u-button text="提交订单" shape="circle" color="linear-gradient( 90deg, #FFCC48 0%, #FF984E 100%)"
						size="small" @click="onNav"></u-button>
				</view>
			</view>
		</view>
		<view class="cartTotal" :style="{ bottom: safeBottom + 'px',width: screenWidth + 'px' }" v-else>
			<view class="row align_item_c">
				<radio :checked="allSelected" color="#FF3F00" style="transform:scale(0.8)" @click="selectAllAction" />
				<view class="cart-choose" @click="selectAllAction">全选</view>
			</view>
			<view class="row minau minright0">
				<u-button text="删除" shape="circle" color="linear-gradient( 90deg, #FFCC48 0%, #FF984E 100%)"
					size="small" @click="deleteItem"></u-button>
			</view>
		</view>
		<!-- 底部选项卡 -->
		<view :style="{ height: safeBottom - 11 +'px'}"></view>
		<!-- 底部tab -->
		<block>
			<userTab :item="2"></userTab>
		</block>
		<!-- 底部tab -->
	</view>
</template>

<script>
	import userTab from "@/components/tabBar/userTab.vue"
	import Decimal from 'decimal.js';
	export default {
		components: {
			userTab
		},
		data() {
			return {
				// totalPrice: 0,
				// totalIntegral: 0,
				// totalNum: 0,
				isEdit: false,
				allSelected: 1,
				page: 1,
				topHight: '',
				safeBottom: '',
				screenWidth: '',
				user_id: '',
				status: 'nomore',
				loadmore: [],
				checkData: [],
				cart: [],
				list: [],
			}
		},
		onLoad() {
			let app = uni.getSystemInfoSync()
			let safeAreaBottom = app.screenHeight - app.safeArea.bottom
			this.topHight = app.statusBarHeight + 4
			this.screenWidth = app.screenWidth - 30
			this.safeBottom = safeAreaBottom + 51
		},
		onShow() {
			//当前页面展示的时候他就执行该生命周期
			const token = uni.getStorageSync('token');
			this.user_id = uni.getStorageSync('user_id');
			if (token) {
				//如果存在token
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 10 // 滚动动画时长，默认300ms
				});
				this.page = 1
				this.getCar()
				//按正常逻辑来讲 登录成功 我们是不是需要向服务器获取用户的信息？
				//那么我们一起来获取用户信息
			} else {

				uni.showToast({
					title: '您还未登录，正在前往登录',
					icon: 'none'
				})
				setTimeout(function() {
					uni.navigateTo({
						url: "/mypackage/user/login"
					})
				}, 1000)
			}
		},
		onReachBottom() {
			if (this.page < 0) return;
			this.status = 'loading';
			this.page = ++this.page
			this.getCar()
			setTimeout(() => {
				console.log(this.loadmore);
				if (this.loadmore.length == 0) this.status = 'nomore';
				else this.status = 'loading';
			}, 1000)
		},
		computed: {
			total() {
				let totalIntegral = new Decimal(0);
				let prices = new Decimal(0);
				let quantity = 0;
				this.list.forEach(item => {
					item.products.forEach(goodItem => {
						let old_price = prices
						let Integral = totalIntegral
						if (goodItem.goodsSelected == 1) {
							prices = new Decimal(goodItem.specs.selling_price).mul(Decimal(goodItem.specs
								.specs_num))
							prices = old_price.add(prices)
							totalIntegral = new Decimal(goodItem.specs.sore).mul(Decimal(goodItem.specs
								.specs_num))
							totalIntegral = Integral.add(totalIntegral)
							quantity += goodItem.specs.specs_num
						} else {
							prices = new Decimal(0)
							prices = old_price.add(prices)
							totalIntegral = new Decimal(0)
							totalIntegral = Integral.add(totalIntegral)
							quantity += 0
						}
						// goodItem.goodsSelected == 1 ? prices += goodItem.goods_price * goodItem
						// 	.goods_num :
						// 	;
						// goodItem.goodsSelected == 1 ?  :
						// 	;
						// goodItem.goodsSelected == 1 ? totalIntegral += goodItem.goods_integral * goodItem
						// 	.goods_num :
						// 	;

					})
				})
				
				return {
					totalNum: quantity,
					totalPrice: prices.toFixed(2),
					totalIntegral: totalIntegral.toFixed(0),
				}
			}
		},
		methods: {
			async getCar() {
				let {
					code,
					message,
					data
				} = await this.$com.fetchGet("car/car_list/" + this.user_id, {
					page: this.page
				})
				if (code == 200) {
					let shopSelected = 1
					let goodsSelected = 1
					data.items.forEach((item, index) => { //js遍历数组
						item.shopSelected = shopSelected
						item.products.forEach((items, index) => { //js遍历数组
							items.goodsSelected = goodsSelected
						});
					});
					if (this.page != 1) {
						this.loadmore = data.items
						for (var i = 0; i < data.items.length; i++) {
							this.list.push(data.items[i]); // 加载的数据追加在上一页后面
						}
					} else {
						this.loadmore = data.items
						this.list = data.items
					}
				} else if (code == 500) {
					this.list = data
					this.loadmore = data
				} else {
					console.log(message);
				}
			},
			async getCarnum(e, id) {
				let {
					code,
					message,
					data
				} = await this.$com.fetch("car/UserCar_up/" + id, {
					user_id: this.user_id,
					specs_num: e.value
				})
				if (code == 200) {
					this.getCar()
				} else {
					console.log(message);
				}
			},
			async getDelete(ids) {
				let {
					code,
					message,
					data
				} = await this.$com.fetchDel("car/Del_car", {
					ids: {
						ids
					}
				})
				if (code == 200) {
					uni.showToast({
						icon: "none",
						title: "删除成功！"
					})
					this.getCar()
				} else {
					uni.showToast({
						icon: "none",
						title: message
					})
				}
			},
			onNav() {
				var all = []
				this.list.forEach((items, inx) => { //js遍历数组
					if (items.shopSelected == 1) {
						let cartarr = {}
						cartarr["stores_name"] = items.shop.stores_name
						cartarr["stores_logo"] = items.shop.stores_logo
						cartarr["stores_id"] = items.shop.id
						cartarr["products"] = []
						items.products.forEach((item, index) => { //js遍历数组
							if (item.goodsSelected == 1) {
								cartarr["products"].push(item)
							}
						});
						all.push(cartarr)
						console.log(all);
					}
				});
				uni.navigateTo({
					url: '/indexpackage/user/place_order?list=' + JSON.stringify(all)
				});
			},
			shopselect(shopItem, goodItem) {
				//遍历此店铺中商品 并全部选择
				if (shopItem.shopSelected == 0) {
					shopItem.shopSelected = 1
					shopItem.products.map(goodItem => {
						goodItem.goodsSelected = 1;
						this.cart.push(goodItem)
					});
				} else {
					shopItem.shopSelected = 0
					shopItem.products.map(goodItem => {
						goodItem.goodsSelected = 0;
					});
					this.cart = this.cart.filter((item) => {
						return item.id != shopItem.products[0].id
					})
				}
				this.changeSelectAllBtn();
			},
			// 选择商品
			goodSelect(shopItem, goodItem) {

				this.checkData.push(goodItem)
				// 如果商品没选中 则不选中店铺
				if (goodItem.goodsSelected == 0) {
					goodItem.goodsSelected = 1
					shopItem.shopSelected = 1;
					//店铺中商品都满足条件 则返回true
					const shopS = shopItem.products.every(goodItem => {
						return goodItem.goodsSelected == 1;
					});
					//商品都选中  则店铺选中
					if (shopS) {
						shopItem.shopSelected = 1;
					}
					this.cart.push(goodItem)
				} else {
					goodItem.goodsSelected = 0
					// shopItem.shopSelected = 0;
					const shopS = shopItem.products.every(goodItem => {
						return goodItem.goodsSelected == 0;
					});
					//商品都选中  则店铺选中
					if (shopS) {
						shopItem.shopSelected = 0;
					} else {
						shopItem.shopSelected = 1;

					}
					this.cart.map((el, index) => {
						if (el.cart_id == goodItem.cart_id) {
							this.cart.splice(index, 1)
						}
					})
				}
				//监听全选按钮状态
				this.changeSelectAllBtn(shopItem);
			},
			// 选择全部
			selectAllAction() {
				//遍历数据数组--遍历店铺  修改选择
				if (this.allSelected == 0) {
					this.allSelected = 1
					this.cart = []
					this.list.map(shopItem => {
						shopItem.shopSelected = 1;
						shopItem.products.map((goodItem, index) => {
							this.cart.push(goodItem)
							goodItem.goodsSelected = 1;
						});
					});
				} else {
					//反选
					this.allSelected = 0
					this.list.map(shopItem => {
						shopItem.shopSelected = 0;
						shopItem.products.map(goodItem => {
							this.cart = []
							goodItem.goodsSelected = 0;
						});
					});
				}
				// this.price()
				// this.quantity()
				// this.integral()
			},
			/* 选择店铺或者商品 监听全选按钮状态 */
			changeSelectAllBtn(shopItem) {
				const selectAll = this.list.every(shopItem => {
					return shopItem.shopSelected == 1;
				});
				var shopS = true
				if (shopItem) {
					shopS = shopItem.products.every(goodItem => {
						return goodItem.goodsSelected == 1;
					});
				}
				if (selectAll && shopS) {
					this.allSelected = 1
				} else {
					this.allSelected = 0

				}
			},
			// 删除单个数据
			deleteItem() {
				let ids = []
				this.list.forEach(item => {
					item.products.forEach(goodItem => {
						if (goodItem.goodsSelected == 1) {
							ids.push(goodItem.car_id)
						}
					})
				})
				ids = ids.map(item => (item))
				// ids = ids.toLocaleString()
				console.log(ids);
				if (ids.length != 0) {
					this.getDelete(ids.toString())
				}

			},
			tab() {
				this.isEdit = !this.isEdit
			},
			valChange(e) {}
		}
	}
</script>

<style scoped lang="less">
	.head_back {
		background: linear-gradient(63deg, #FF515E 0%, #FF7F3E 100%), linear-gradient(167deg, #FF6B4A 0%, rgba(255, 123, 77, 0) 100%);

	}

	.content {
		.cartShop {
			margin-top: 30rpx;
			box-shadow: 0 0 9rpx 3rpx #ccc;
			background-color: white;
			border-radius: 10rpx;
			margin-left: 16rpx;
			margin-right: 16rpx;
			margin-bottom: 20rpx;
			overflow: hidden;
		}

		.cartPad {
			margin: 0 20rpx;
		}

		.cartName {
			font-size: 29rpx;
			color: #333333;
			display: flex;
			align-items: center;
		}

		.cart-xxkbk {
			width: 50rpx;
			height: 100rpx;

			radio {
				margin-top: 30rpx;
			}
		}

		.cartName-box {
			height: 30rpx;
			display: flex;
			align-items: center;
		}

		.cartName-img {
			width: 50rpx;
			height: 50rpx;
			margin: 0 10rpx;
		}

		.cartDetail-imgs {
			width: 200rpx;
			height: 160rpx;
		}

		.cartNum {
			display: flex;
			justify-content: space-between;
			align-items: center;
		}
	}

	.cartTotal {
		width: 100%;
		background-color: white;
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		position: fixed;
		left: 0;
		z-index: 10;
		/* #ifdef H5 */
		// bottom: 100rpx;
		/* #endif */
	}

	.cart-num {
		font-size: 31rpx;
		color: #ffa40c;
		text-align: right;
		padding-right: 11rpx;
	}

	.cart-numTxt {
		font-size: 26rpx;
		color: #4A4A4A;
		font-weight: 600rpx;
	}
</style>